<template>
  <div class="interact-form">
    <a-form :label-col="{ span: labelCol }" :wrapper-col="{ span: wrapperCol }">
      <div class="panel-title" @click="showFlag = !showFlag">
        <div class="panel-title-hr"></div>
        交互
        <a-icon :type="showFlag ? 'down' : 'right'" />
      </div>
      <div v-show="showFlag">
        <a-form-item v-show="filterName" label="筛选字段">
          <span class="ant-form-text">
            {{ filterName }}
          </span>
        </a-form-item>
        <a-form-item :label-col="{ span: 12 }" :wrapper-col="{ span: 24 }">
          <span slot="label">
            关联图表&nbsp;
            <a-tooltip title="如需多级联动，多级间的图表都需配置关联关系">
              <span
                style="cursor: pointer;"
                @mouseover="annotationHover()"
                @mouseout="annotationOut()"
              >
                <a-icon-font
                  v-show="isAnnotationHover"
                  type="iconinfo-cirlce-obeifen"
                />
                <a-icon-font
                  v-show="!isAnnotationHover"
                  type="iconinfo-cirlce-o"
                />
              </span>
            </a-tooltip>
          </span>
          <div class="form-select">
            <div class="select-all">
              <a-checkbox
                :indeterminate="indeterminate"
                :checked="checkAll"
                @change="onCheckAllChange"
              >
                全选
              </a-checkbox>
            </div>
            <a-checkbox-group v-model="copyFormData" @change="onChange">
              <template v-for="item in relateWidgets">
                <!-- 当widgetId 在 被联动的列表中 并且，还没被勾选 -->
                <a-popconfirm
                  v-if="
                    connectedChart.includes(item.widgetId) &&
                    !copyFormData.includes(item.widgetId)
                  "
                  :key="item.value"
                  placement="topLeft"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="confirm(item)"
                >
                  <a-icon-font
                    slot="icon"
                    type="iconinfo-cirlce-obeifen"
                  ></a-icon-font>
                  <template slot="title">
                    <span> {{ generateHintText(item) }}</span>
                  </template>
                  <a-checkbox
                    :key="item.value"
                    :value="item.value"
                    :disabled="item.disabled"
                  >
                    <a-tooltip v-if="item.disabled" placement="topLeft">
                      <template slot="title">
                        当前图表无法设置联动，请检查其数据表内容。
                      </template>
                      <span class="text-ellipsis">{{ item.label }}</span>
                    </a-tooltip>
                    <span v-else class="text-ellipsis"> {{ item.label }} </span>
                  </a-checkbox>
                </a-popconfirm>

                <a-checkbox
                  v-else
                  :key="item.value"
                  :value="item.value"
                  :disabled="item.disabled"
                >
                  <a-tooltip v-if="item.disabled" placement="topLeft">
                    <template slot="title">
                      当前图表无法设置联动，请检查其数据表内容。
                    </template>
                    <span class="text-ellipsis">{{ item.label }}</span>
                  </a-tooltip>
                  <span v-else class="text-ellipsis"> {{ item.label }} </span>
                </a-checkbox>
              </template>
            </a-checkbox-group>
          </div>
        </a-form-item>
      </div>
    </a-form>
  </div>
</template>

<script lang="ts">
import { Vue, Prop, Component, Watch } from 'vue-property-decorator'
import CheckboxGroup from '@/components/studio/data/set-params/linkage-form/CheckboxGroup.vue'
import VisualizationStore from '@/store/modules/visualization'
import { cloneDeep, isEqual } from 'lodash'

export interface KeyValue {
  [key: string]: any
}

@Component({
  components: {
    CheckboxGroup,
  },
})
export default class InteractForm extends Vue {
  @Prop({ default: () => [] }) relateWidgets!: KeyValue[] //  关联图表列表
  @Prop({ default: () => '' }) currentName!: any //  关联图表列表
  @Prop({
    type: Number,
    required: false,
    default() {
      return 8
    },
  })
  labelCol!: number

  @Prop({
    type: Number,
    required: false,
    default() {
      return 16
    },
  })
  wrapperCol!: number

  @Prop({
    type: Array,
    required: true,
    default(): any {
      return []
    },
  })
  checkedWidgets!: any //  勾选的选项 如：[12394, 15869]

  @Prop({
    type: String,
    required: false,
    default() {
      return ''
    },
  })
  filterName!: String //  筛选字段

  private get connectedChart() {
    return VisualizationStore.connectedList
  }

  private get interactList() {
    return VisualizationStore.interactList
  }

  public indeterminate: boolean = false
  public checkAll: boolean = false

  private isAnnotationHover = false
  public annotationHover() {
    this.isAnnotationHover = true
  }
  public annotationOut() {
    this.isAnnotationHover = false
  }

  private copyFormData: any = []

  public mounted() {
    this.copyFormData = cloneDeep(this.checkedWidgets)
    this.onChange(this.copyFormData)
  }

  @Watch('checkedWidgets', { deep: true })
  public watchFormData(newValue: any, oldValue: any) {
    if (isEqual(newValue, oldValue)) {
      return
    }
    this.copyFormData = cloneDeep(this.checkedWidgets)
    this.onChange(this.copyFormData)
  }

  private generateHintText(target: any) {
    const rules = this.interactList.find((item: any) => {
      return item.child === target.widgetId
    })
    return `${target.label}已经被${rules.parents[0].label}关联，若此处在进行关联，${this.currentName}将以交集作为过滤条件后进行渲染，是否继续?`
  }

  private confirm(item: any) {
    console.log('test')
    this.copyFormData.push(item.widgetId)
    this.onChange(this.copyFormData)
  }

  public onChange(checkedList: any[]) {
    if (checkedList) {
      this.indeterminate =
        checkedList.length > 0 && checkedList.length < this.relateWidgets.length
      this.checkAll = checkedList.length === this.relateWidgets.length
      this.$nextTick(() => {
        this.$emit('change', checkedList)
      })
    }
  }

  // 全选
  public onCheckAllChange($event: any) {
    Object.assign(this, {
      indeterminate: false,
      checkAll: $event.target.checked,
    })
    const checkedList: any = $event.target.checked
      ? this.relateWidgets.map((item: any) => item.value)
      : []
    this.copyFormData = checkedList
    this.$nextTick(() => {
      this.$emit('change', checkedList)
    })
  }

  private showFlag: boolean = true // 是否展开面板

  beforeDestroy() {
    this.indeterminate = false
    this.checkAll = false
  }

  get gridList(): Array<any> {
    return VisualizationStore.gridList
  }

  @Watch('gridList', { deep: true })
  handleGridListChange(newValue: any) {
    if (newValue) {
      this.parseInteractInfo()
      console.log('again~~~~~~')
    }
  }

  private parseInteractInfo() {
    // forEach this.gridList item - interactionJson - relateWidgets
    const result: any = []
    this.gridList.forEach((item: any) => {
      if (
        item.interactionJson?.relateWidgets &&
        item.interactionJson?.relateWidgets.length > 0
      ) {
        const list = item.interactionJson?.relateWidgets
        list.forEach((widget: any) => {
          if (widget.status === 'connected') {
            const index = result.findIndex(
              (i: any) => i.child === widget.widgetId
            )
            if (index >= 0) {
              result[index].parents.push({
                widgetId: item.widgetId,
                label: item.chartOptions.title
                  ? item.chartOptions.title
                  : item.widgetId,
              })
            } else {
              result.push({
                child: widget.widgetId,
                parents: [
                  {
                    widgetId: item.widgetId,
                    label: item.chartOptions.title
                      ? item.chartOptions.title
                      : item.widgetId,
                  },
                ], // 后续需要push
              })
            }
          }
        })
      }
    })
    // this.interactRelateList = result
    //  store in vuex
    VisualizationStore.setInteractList(result)

    const connectedList: any = []
    //  get connected widget list; [1,2,3,4]
    result.forEach((item: any) => {
      connectedList.push(item.child)
    })
    //  store in vuex
    VisualizationStore.setConnectedList(connectedList)
  }
}
</script>

<style lang="less" scoped>
.interact-form {
  margin-bottom: 100px;
}

.panel-title {
  font-weight: bolder;
  height: 40px;
  line-height: 40px;
  margin-top: 4px;
  position: relative;
  width: 100%;

  .anticon {
    font-size: 8px;
    font-weight: normal;
    height: 40px;
    line-height: 40px;
    position: absolute;
    right: 10px;
  }

  .panel-title-hr {
    background-color: #e9e9e9;
    height: 1px;
    left: -16px;
    position: absolute;
    right: -20px;
  }
}

.form-select {
  background: #f1f1f1;
  border-radius: 4px;
  padding: 8px;
}

.text-ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: bottom;
  white-space: nowrap;
  width: 190px;
}

/deep/ .ant-checkbox-wrapper {
  width: 100%;
}

/deep/ .ant-checkbox-wrapper + .ant-checkbox-wrapper {
  margin-left: 0;
}

/deep/ .ant-checkbox-group-item {
  width: 100%;
}

/deep/ .ant-form-item-label {
  text-align: left;
}

/deep/ .ant-form-item.vertical {
  .ant-col {
    width: 100%;
  }
}

/deep/ .ant-form-item {
  margin-bottom: 0;
}

/deep/ .ant-form-item-label > label::after {
  content: '';
}
</style>
